<template>
  <view class="wallet-container">
	  <status-bar bgColor="#4c9bfb"></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">我的钱包</view>
      <view class="help-btn" @click="showHelp">
        <uni-icons type="help" size="24" color="#fff"></uni-icons>
      </view>
    </view>
    
    <!-- 余额展示区域 -->
    <view class="balance-area">
      <view class="balance-title">可提现金额 (元)</view>
      <view class="balance-amount">{{availableBalance}}</view>
      <view class="withdraw-btn" @click="applyWithdraw">申 请 提 现</view>
    </view>
    
    <!-- 账户信息区域 -->
    <view class="account-info" v-if="false">
      <view class="info-item">
        <view class="info-label">结算中余额 (元)</view>
        <view class="info-value">{{settlingBalance}}</view>
      </view>
      <view class="info-item">
        <view class="info-label">累计收益 (元)</view>
        <view class="info-value">{{totalIncome}}</view>
        <view class="info-icon">
          <uni-icons type="info" size="18" color="#999"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 功能列表区域 -->
    <view class="function-list">
      <view class="list-cell list-cell-arrow" @click="navigateTo('/pages/mine/income-details')">
        <view class="menu-item-box">
          <text>收支明细</text>
        </view>
      </view>
      <view class="list-cell list-cell-arrow" @click="navigateTo('/pages/mine/withdraw-records')">
        <view class="menu-item-box">
          <text>提现记录</text>
        </view>
      </view>
    </view>
	
    <view class="perfect-content">
	
	<!-- 身份证上传区域 -->
	<view class="id-card-section">
		<!-- <view class="section-title">身份证信息</view> -->
		  <view class="id-card-upload-area">
		    <view class="id-card-item">
		      <image v-if="idCardFront" :src="idCardFront" class="id-card-image" mode="aspectFit" @click="previewImage(idCardFront)"></image>
		      <image v-else src="/static/images/idcatd_front.png" class="id-card-image" mode="aspectFit" @click="uploadIdCard('front')"></image>
		      <view class="upload-btn" @click="uploadIdCard('front')">{{idCardFront ? '重新上传' : '上传正面'}}</view>
		    </view>
		    <view class="id-card-item">
		      <image v-if="idCardBack" :src="idCardBack" class="id-card-image" mode="aspectFit" @click="previewImage(idCardBack)"></image>
		      <image v-else src="/static/images/idcard_back.png" class="id-card-image" mode="aspectFit" @click="uploadIdCard('back')"></image>
		      <view class="upload-btn" @click="uploadIdCard('back')">{{idCardBack ? '重新上传' : '上传反面'}}</view>
		    </view>
		  </view>
		</view>
	</view>
  </view>
</template>

<script>
import {  allInCome } from '@/api/app/master/transactionlog.js'
import { addZjbMaster, getMyInfo } from '@/api/app/master/master';
import { uploadFile } from '@/api/app/master/file'

export default {
  data() {
    return {
      availableBalance: '0.00',
      settlingBalance: '0.00',
      totalIncome: '0.00',
	  idCardFront: '',
	  idCardBack: '',
	  myInfo: {}
    }
  },
  onLoad() {
    // 这里可以调用接口获取钱包数据
    this.getWalletInfo();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    showHelp() {
      uni.showModal({
        title: '帮助说明',
        content: '可提现金额为已结算完成的收益，结算中余额为正在结算的收益，通常需要T+1天完成结算。',
        showCancel: false
      });
    },
    applyWithdraw() {
		if (!this.idCardFront || !this.idCardBack) {
		  return uni.showToast({ title: '请上传身份证照片', icon: 'none' });
		}
        // TODO 测试先注释
       if (parseFloat(this.availableBalance) <= 0) {
         uni.showToast({
           title: '可提现金额为0，无法提现',
           icon: 'none'
         });
         return;
       }
      
      uni.navigateTo({
        url: `/pages/mine/withdraw?amount=${this.availableBalance}`
      });
    },
    navigateTo(url) {
      uni.navigateTo({
        url: url
      });
    },
    getWalletInfo() {
      // 模拟接口调用，实际项目中应该调用真实接口
      // 可以使用 uni.request 调用后端接口获取钱包信息
      allInCome().then(res => {
        if (res.code === 200 && res.data) {
          const income = res.data;
          this.totalIncome = typeof income === 'number' ? 
            income.toFixed(2) : String(income);
            console.log('设置总收入为:', this.totalIncome);
        }
      }).catch(err => {
        console.error(err);
      });
      getMyInfo().then(res => {
        if (res.code === 200 && res.data) {
          console.log('设置个人信息为:', res.data);
            const info = res.data;
            this.availableBalance = typeof info.accountBalance === 'number' ? 
              info.accountBalance.toFixed(2) : String(info.accountBalance);
              console.log('设置可用余额为:', this.availableBalance);
			  this.idCardFront = info.pictureFrontId;
			  this.idCardBack = info.pictureBackId;
			  this.myInfo = info;
        }
      }).catch(err => {
        console.error(err);
      });
      


      setTimeout(() => {
        this.settlingBalance = '0.00';
      }, 500);
    },
	
	// 预览图片
	previewImage(url) {
	  if (!url) return;
	  uni.previewImage({
	    urls: [url],
	    current: url
	  });
	},
	
	uploadIdCard(type) {
	  uni.chooseImage({
	    count: 1,
	    sizeType: ['compressed'],
	    sourceType: ['album', 'camera'],
	    success: (res) => {
	      const filePath = res.tempFilePaths[0];
		  // 生成唯一文件名
		  const timestamp = Date.now()
		  const random = Math.random().toString(36).substring(2, 8)
		  const fileName = `idcard_photos/${timestamp}_${random}.jpg`
		  console.log('图片路径:', filePath)
		  uni.showLoading({ title: '上传中...' });
		  uploadFile(fileName, filePath)
	        .then(result => {
	          console.log('result', result);
	          if (type === 'front') {
				this.myInfo.pictureFrontId = result.url;
	          } else {
				this.myInfo.pictureBackId = result.url;
	          }
			  uni.showLoading({ title: '提交中...' });
			  addZjbMaster(this.myInfo).then(() => {
				  if (type === 'front') {
				    this.idCardFront = result.url;
				  } else {
				    this.idCardBack =  result.url;
				  }
				  uni.showToast({ title: '提交成功', icon: 'success' });
			  }).catch(err => {
				  console.error(err);
				  uni.showToast({ title: '提交失败', icon: 'success' });
			  }).finally(() => {
				  uni.hideLoading();
			  })
	        }).catch(err => {
				  console.error(err);
				  uni.showToast({ title: '上传失败', icon: 'success' });
			  }).finally(() => {
				  uni.hideLoading();
			  })
	    },
	    fail: () => {
	      uni.showToast({ title: '图片选择失败', icon: 'none' })
	    }
	  })
	},
  }
}
</script>

<style lang="scss" scoped>
.wallet-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #4c9bfb;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
}

.help-btn {
  position: absolute;
  right: 30rpx;
}

/* 余额展示区域 */
.balance-area {
  background-color: #4c9bfb;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
}

.balance-title {
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.balance-amount {
  font-size: 80rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
}

.withdraw-btn {
  width: 80%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #fff;
  color: #4c9bfb;
  text-align: center;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
}

/* 账户信息区域 */
.account-info {
  background-color: #fff;
  display: flex;
  padding: 30rpx 0;
  margin-bottom: 20rpx;
}

.info-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.info-item:first-child::after {
  content: '';
  position: absolute;
  right: 0;
  top: 20%;
  height: 60%;
  width: 1px;
  background-color: #eee;
}

.info-label {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.info-value {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.info-icon {
  margin-left: 10rpx;
  display: inline-block;
}

/* 功能列表区域 */
.function-list {
  background-color: #fff;
}

.list-cell {
  position: relative;
  width: 100%;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
  padding: 26rpx 30rpx;
}

.list-cell::after {
  content: '';
  position: absolute;
  border-bottom: 1px solid #eaeef1;
  transform: scaleY(0.5) translateZ(0);
  transform-origin: 0 100%;
  bottom: 0;
  right: 0;
  left: 0;
  pointer-events: none;
}

.list-cell-arrow::before {
  content: ' ';
  height: 10px;
  width: 10px;
  border-width: 2px 2px 0 0;
  border-color: #c0c0c0;
  border-style: solid;
  transform: matrix(0.5, 0.5, -0.5, 0.5, 0, 0);
  position: absolute;
  top: 50%;
  margin-top: -6px;
  right: 30rpx;
}

.menu-item-box {
  width: 100%;
  display: flex;
  align-items: center;
  font-size: 32rpx;
}

.perfect-content {
  padding: 30rpx;
}

.id-card-section {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.id-card-upload-area {
  display: flex;
  justify-content: space-between;
}

.id-card-item {
  width: 48%;
  height: 180rpx;
  background-color: #e8f4ff;
  border-radius: 8rpx;
  overflow: hidden;
}

.id-card-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.camera-icon {
  font-size: 60rpx;
  color: #0088ff;
  font-family: "iconfont";
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #0088ff;
}

.id-card-image {
  width: 100%;
  height: 140rpx;
}

.upload-btn {
  height: 40rpx;
  line-height: 40rpx;
  font-size: 24rpx;
  color: #0088ff;
  text-align: center;
  background-color: #e8f4ff;
}
</style>